package com.tanhua.manage.interceptor;

import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("==========请求的路径：==========="+request.getRequestURL());

        //获取头信息
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ","");

        //如果没有token，权限不足，返回false
        if(token == null){
            //token为null，状态码401
            response.setStatus(401);
            return false;
        }

        //调用service根据token查询用户
        Admin admin = adminService.findUserByToken(token);
        if(admin == null){
            //token为null，状态码401
            response.setStatus(401);
            return false;
        }

        //将对象存入threadLocal
        AdminHolder.set(admin);

        return true;

    }
}
